package com.actions.bluetoothbox2.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.actions.bluetoothbox2.R;
import com.actions.ibluz.factory.BluzDeviceFactory;
import com.actions.ibluz.factory.IBluzDevice;

import java.util.List;

public class ConnectionActivity extends Activity {

    private final static int MAX_RETRY_TIMES = 5;
    private ImageView img_connectin;
    private IBluzDevice mBluzConnector;
    private List<DeviceListAdapter.DeviceEntry> mDeviceEntries;
    private int mConnectRetryTimes;
    private AlertDialog mAlertDialog = null;
    private boolean mDiscoveryStarted;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connectin);
        img_connectin = (ImageView) findViewById(R.id.img_connectin);
        mBluzConnector = BluzDeviceFactory.getDevice(this);
//        mBluzConnector.setOnDiscoveryListener(mOnDiscoveryListener);

        img_connectin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(ConnectionActivity.this, BrowserActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    //搜索
    private IBluzDevice.OnDiscoveryListener mOnDiscoveryListener = new IBluzDevice.OnDiscoveryListener() {

        @Override
        public void onConnectionStateChanged(BluetoothDevice device, int state) {
            if (device != null) {
                DeviceListAdapter.DeviceEntry entry = findEntry(device);
                if (entry == null) {
                    entry = new DeviceListAdapter.DeviceEntry(device, state);
                    mDeviceEntries.add(entry);
                }
                Log.i("TAG", "onConnectionStateChanged:" + state + "@" + device.getName());
                if (state == BluzDeviceFactory.ConnectionState.A2DP_FAILURE) {
                    state = BluzDeviceFactory.ConnectionState.A2DP_DISCONNECTED;
                    if (!retry(device)) {
                        Toast.makeText(ConnectionActivity.this, R.string.connection_connect_fail, Toast.LENGTH_SHORT).show();
                        showSetting();
                    }
                } else if (state == BluzDeviceFactory.ConnectionState.SPP_FAILURE) {
                    state = BluzDeviceFactory.ConnectionState.A2DP_CONNECTED;
                    if (!retry(device)) {
                        Toast.makeText(ConnectionActivity.this, R.string.connection_connect_data_fail, Toast.LENGTH_SHORT).show();
                    }
                }
                entry.state = state;
                for (int i = 0; i < mDeviceEntries.size(); i++) {

                }

            }
        }

        @Override
        public void onDiscoveryStarted() {

        }

        @Override
        public void onDiscoveryFinished() {

        }

        @Override
        public void onFound(BluetoothDevice bluetoothDevice) {

        }
    };

    private synchronized DeviceListAdapter.DeviceEntry findEntry(BluetoothDevice device) {
        DeviceListAdapter.DeviceEntry deviceEntry = null;
        for (DeviceListAdapter.DeviceEntry entry : mDeviceEntries) {
            if (entry.device.getAddress().equals(device.getAddress())) {
                deviceEntry = entry;
                break;
            }
        }
        return deviceEntry;
    }

    private boolean retry(BluetoothDevice device) {
        /* FIXME when data connect, it pops a confirm activity, like Lenovo S939/Lenovo S898t+.While select reject,it also connect again and again */
        if (Build.MODEL.contains("Lenovo S939") || Build.MODEL.contains("Lenovo S898t+")) {
            mBluzConnector.disconnect(device);
            return true;
        }
        if (mConnectRetryTimes < MAX_RETRY_TIMES) {
            Log.i("TAG", "retry:" + mConnectRetryTimes);
            mBluzConnector.retry(device);
            mConnectRetryTimes++;
            return true;
        } else {
            mConnectRetryTimes = 0;
            return false;
        }
    }

    private void startDiscovery() {
        mDiscoveryStarted = false;
        mConnectRetryTimes = 0;
        /* in case some device(e.g. LT15i don't send onDiscoveryStarted */
        initEntry();
        mBluzConnector.startDiscovery();
    }

    private void initEntry() {
        if (!mDiscoveryStarted) {
            mDeviceEntries.clear();
        }

        // device cannot be found while connected, so manually add it here
        int state = BluzDeviceFactory.ConnectionState.A2DP_DISCONNECTED;
        BluetoothDevice device = mBluzConnector.getConnectedDevice();
        if (device != null) {
            state = getEntryState(device, BluzDeviceFactory.ConnectionState.SPP_CONNECTED);
        } else {
            device = mBluzConnector.getConnectedA2dpDevice();
            if (device != null) {
                state = getEntryState(device, BluzDeviceFactory.ConnectionState.A2DP_CONNECTED);
            }
        }
        if (device != null && findEntry(device) == null) {
            mDeviceEntries.add(new DeviceListAdapter.DeviceEntry(device, state));
        }
//        mDeviceAdapter.notifyDataSetChanged();
    }

    private int getEntryState(BluetoothDevice device, int defState) {
        for (DeviceListAdapter.DeviceEntry entry : mDeviceEntries) {
            if (entry.device.equals(device)) {
                return entry.state;
            }
        }
        return defState;
    }

    private void showSetting() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ConnectionActivity.this);
        builder.setTitle(R.string.dialog_title_info);
        builder.setMessage(R.string.dialog_show_setting_message);
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.dialog_show_setting_positive, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialogShowSetting();

                Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialogShowSetting();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.show();
    }

    private void dismissDialogShowSetting() {
        if (mAlertDialog != null) {
            mAlertDialog.dismiss();
            mAlertDialog = null;
        }
    }
}
